<template>
    <div class="confirm-order-container">
        <!-- 导航栏 -->
        <TmallNavBar>
            <template #left><i class="icon iconfont icon-zuojiantou"></i></template>
            <template #default>确认订单</template>
            <template #right><i class="icon iconfont icon-shouye1" @click="$router.push({path: '/'})"></i></template>
        </TmallNavBar>

        <!-- 主体内容 -->
        <div class="confirm-order-main">
            <!-- 收货地址开始 -->
            <div v-if="userStore.deliveryAddr" class="shipment" @click="showDeliveryAddr">
                <div class="address-box">
                    <div class="location-icon">
                        <van-icon name="location" color="#27BA9B"/>
                    </div>
                    <div class="address-box-content">
                        <div class="user">
                            {{ userStore.deliveryAddr.name }} {{ userStore.deliveryAddr.mobile }}
                        </div>
                        <div class="address">
                            {{ userStore.deliveryAddr.region }} {{ userStore.deliveryAddr.address }}
                        </div>
                    </div>
                </div>
                <div class="arrows">
                    <span class="iconfont icon-youjiantoucu"></span>
                </div>
            </div>

            <!-- 请选择收货地址 -->
            <div v-else class="shipment" @click="$router.push('/deliveryAddress')">
                <div class="select-address"> 请选择收货地址 </div>
                <span class="iconfont icon-youjiantoucu"></span>
            </div>

            <!-- 选择收货地址弹层 -->
            <van-popup
                v-model:show="isShowPopup"
                position="bottom"
                background-color="#fff"
            >
                <div class="address-title">
                    <!-- 标题 -->
                    <div class="title">选择收货地址</div>
                    <!-- 关闭按钮 -->
                    <span class="close iconfont icon-guanbi" @click="isShowPopup = false"></span>
                </div>
                <div class="address-list">
                    <!-- 收货地址项 -->
                    <div class="item" v-for="(item, index) in deliveryAddrList" :key="index">
                        <div class="item-content" 
                            @click="selectDeliveryAddr(item)" 
                            :class="{active:item.id == userStore.deliveryAddr.id ? true : false}"
                        >
                            <div class="address-icon">
                                <van-icon name="location" color="#27BA9B"/>
                            </div>

                            <div class="address-box">
                                <div class="address-name-box">
                                    <span class="address-name">{{ item.name }}</span>
                                    <van-tag
                                        v-if="item.is_default == 1"
                                        color="#27BA9B"
                                        mark
                                        type="success"
                                    >默认</van-tag>
                                </div>
                                <span class="address-contact">{{item.mobile}}</span>
                                <div class="address-locate">{{ item.region }} {{ item.address }}</div>
                            </div>
                        </div>
                    </div>

                    <div class="address-add-btn">
                        <van-button
                            type="primary"
                            color="#27BA9B"
                            @click="$router.push('/deliveryAddress')"
                        >新增收货地址+</van-button>
                    </div>
                </div>
            </van-popup>
            <!-- 收货地址结束 -->

            <!-- 直接购买模式 -->
            <div class="buy-goods" v-if="mode == 1">
            <div class="item"
                @click="$router.push('/goodsDetail?goods_id='+orderStore.createOrderParams?.goods_id)"
            >
                <van-image class="picture" :src="orderStore.createOrderParams?.cover_url"/>
                <div class="meta">
                    <div class="name ellipsis"> {{ orderStore.createOrderParams?.name }} </div>
                    <div class="attrs">{{ orderStore.createOrderParams?.goods_sepc_option_text }}</div>
                    <div class="prices">
                        <div class="pay-price symbol">
                            {{ (orderStore.createOrderParams?.price/100).toFixed(2) }}
                        </div>
                        <div class="price symbol">
                            {{ (orderStore.createOrderParams?.price/100).toFixed(2) }}
                        </div>
                    </div>
                    <div class="count">x{{ orderStore.createOrderParams?.num }}</div>
                </div>
            </div>
            </div>

            <!-- 购物车结算模式 -->
            <div class="buy-goods" v-else>
                <div class="item"
                    v-for="item in cartStore.checkedList"
                    :key="item.id"
                    @click="$router.push('/goodsDetail?goods_id='+item.goods_id)"
                >

                    <img class="picture" v-img-lazy="global.MINIO_FILE_DOMAIN + item.goods.cover_url" />

                    <div class="meta">
                        <div class="name ellipsis"> {{ item.goods.name }} </div>
                        <div class="attrs">{{ item.goods_sepc_option_text }}</div>
                        <div class="prices">
                            <div class="pay-price symbol">{{ (item.new_price/100).toFixed(2) }}</div>
                            <div class="price symbol">{{ (item.goods.price/100).toFixed(2) }}</div>
                        </div>
                        <div class="count">x{{ item.num }}</div>
                    </div>
                </div>
            </div>

            <!-- 配送及支付方式 -->
            <div class="related">
            <div class="item" @click="isShowDelivery = true">
                <span class="text">配送时间</span>
                <div class="icon-fonts picker">{{ activeDelivery.text }}</div>
            </div>

            <van-popup v-model:show="isShowDelivery" round position="bottom">
                <van-picker
                    :columns="deliveryList"
                    @cancel="isShowDelivery = false"
                    @confirm="onConfirmDelivery"
                />
            </van-popup>

            <div class="item">
                <span class="text">订单备注</span>
                <van-field v-model="buyerMessage" placeholder="选填，建议留言前先与商家沟通确认" />
                <!-- <input
                    class="input"
                    :cursor-spacing="30"
                    placeholder="选题，建议留言前先与商家沟通确认"
                    v-model="buyerMessage"
                /> -->
            </div>
            </div>

            <!-- 支付金额 -->
            <div class="settlement">
                <div class="item">
                    <span class="text">商品总价: </span>
                    <span class="number symbol" v-if="mode == 1">
                        {{ (orderStore.createOrderParams?.price/100).toFixed(2) }}
                    </span>
                    <span class="number symbol" v-else>
                        {{ (cartStore.checkedAmount/100).toFixed(2) }}
                    </span>
                </div>
                <div class="item">
                    <span class="text">运费: </span>
                    <span class="number">免费包邮</span>
                </div>
            </div>
        </div>

    </div>

    <!-- 吸底工具栏 -->
    <div class="toolbar">
        <div class="total-pay symbol">
            <span class="number" v-if="mode == 1">
                {{ ((orderStore.createOrderParams?.price*orderStore.createOrderParams?.num)/100).toFixed(2) }}
            </span>
            <span class="number" v-else>
                {{ (cartStore.checkedAmount/100).toFixed(2)}}
            </span>
        </div>
        <div v-if="mode == 1" @click="handleCreateOrder" class="button"> 提交订单 </div>
        <div v-else @click="handleCreateOrder" class="button" :class="{ disabled: cartStore.checkedTotal > 0 ? false : true }"> 提交订单 </div>
    </div>
</template>
  
<script setup>
import { computed, ref, inject, onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { useOrderStore } from '@/store/modules/order'
import { useCartStore } from '@/store/modules/cart'
import { useRouter,useRoute } from 'vue-router'
import { reqCreateOrderAPI, reqGenerateOrderAPI } from "@/apis/order";
import { reqUserDeliveryAddrListAPI } from '@/apis/userDeliveryAddr';
import { showSuccessToast, showToast } from 'vant'
  
  

// ---------------------------- 定义全局变量开始 ----------------------------
// 全局属性
const global = inject('global')

// 用户存储
const userStore = useUserStore()

// 购物车存储
const cartStore = useCartStore()

// 订单存储
const orderStore = useOrderStore()

// 订单备注
const buyerMessage = ref('')

// 路由
const route = useRoute()

// 路由器
const router = useRouter()
// ---------------------------- 定义全局变量结束 ----------------------------
  
  

// ---------------------------- 收货地址功能开始 ----------------------------
const deliveryAddrList = ref([])

const getUserDeliveryAddr = async () => {
    const result = await reqUserDeliveryAddrListAPI({status: 1})
    deliveryAddrList.value = result.data.user_delivery_addrs != null ? result.data.user_delivery_addrs : []
    let deliveryAddr = null
    deliveryAddrList.value.forEach((item) => {
        if (item.is_default == 1) {
            deliveryAddr = item
        }
    });

    if (!deliveryAddr) {
        deliveryAddr = deliveryAddrList.value[0]
    }

    userStore.setDeliveryAddr(deliveryAddr)
}
// ---------------------------- 收货地址功能结束 ----------------------------
  


// ------------------------- 选择收货地址功能开始 ----------------------------
const isShowPopup = ref(false)
// 显示收货地址
const showDeliveryAddr = () => {
    isShowPopup.value = true
}

// 选择收货地址
const selectDeliveryAddr = (item) => {
    userStore.setDeliveryAddr(item)
    isShowPopup.value = false
}

// ------------------------- 选择收货地址功能结束 ----------------------------
  
  
// -------------------------- 配送时间功能开始 ------------------------------
// 配送时间
const deliveryList = ref([
    { value: 1, text: '时间不限 (周一至周日)' },
    { value: 2, text: '工作日送 (周一至周五)' },
    { value: 3, text: '周末配送 (周六至周日)' },
])

// 当前配送时间下标
const activeIndex = ref(0)

// 当前配送时间
const activeDelivery = computed(() => deliveryList.value[activeIndex.value])

const isShowDelivery = ref(false)

// 确认配送时间
const onConfirmDelivery = ({selectedOptions}) => {
    console.log('selectedOptions =', selectedOptions);
    activeIndex.value = selectedOptions[0].value - 1
    isShowDelivery.value = false
}
// -------------------------- 配送时间功能结束 ------------------------------


const mode = ref(0)
onMounted(() => {
    mode.value = route.query.mode
    getUserDeliveryAddr()
})
  
  
  
  
// -------------------------- 创建订单功能开始 --------------------------
const handleCreateOrder = async () => {
    if (!userStore.deliveryAddr) {
        showToast('请选择收货地址!')
        return false
    }
    // 下单参数
    let params = {
        platform: 1,
        username: userStore.profile.user.username,
        address_id: userStore.deliveryAddr.id
    }
    
    let result = null
    // 直接下单方式
    if (mode.value == 1) {
        const createOrderParams = orderStore.createOrderParams
        // 判断库存
        if (createOrderParams.num > createOrderParams.inventory_num) {
            showToast('库存不足')
            return false
        }
        
        params.goods_sku_id = createOrderParams.goods_sku_id
        params.num = createOrderParams.num
        result = await reqGenerateOrderAPI(params)
    } else {// 购物车下单方式
        result = await reqCreateOrderAPI(params)
    }
    
    showSuccessToast('下单成功')

    // 跳转订单支付页面
    router.push({path: '/orderDetail', query: {oid: result.data.oid, referer: 'confirmOrder'}})
}
// -------------------------- 创建订单功能结束 --------------------------
</script>
  
<style scoped lang="scss">
.confirm-order-container {
    .confirm-order-main {
        display: flex;
        flex-direction: column;
        margin-top: 55px;
        margin-bottom: 50px;
        // 收货地址
        .shipment {
            display: flex;
            align-items: center;
            margin: 0 10px;
            padding: 15px 20px 15px 0;
            font-size: 13px;
            position: relative;
            background: white;
            justify-content: space-between;
            border-radius: 5px;
            border: 1px solid gainsboro;
            .location-icon {
                font-size: 24px;
                margin-left: 5px;
            }
            .address-box {
                display: flex;
                align-items: center;
                .address-box-content {
                    display: flex;
                    flex-direction: column;
                    .user {
                        color: #333;
                        margin-bottom: 2.5px;
                        font-size: 15px;
                        font-weight: bold;
                    }
                    .address {
                        color: #666;
                    }
                }
            }
            .select-address {
                font-weight: bold;
                margin-left: 10px;
            }
        }

        // 商品信息
        .buy-goods {
            display: flex;
            flex-direction: column;
            margin: 10px;
            padding: 0 10px;
            border-radius: 5px;
            background-color: #fff;
            .item {
                display: flex;
                padding: 15px 0;
                border-top: 1px solid #eee;
        
                &:first-child {
                    border-top: none;
                }
        
                .picture {
                    width: 85px;
                    height: 85px;
                    border-radius: 5px;
                    margin-right: 10px;
                }
        
                .meta {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    position: relative;
                }
        
                .name {
                    height: 35px;
                    font-size: 13px;
                    color: #444;
                }
        
                .attrs {
                    line-height: 1.8;
                    padding: 0 8px;
                    margin-top: 3px;
                    font-size: 12px;
                    align-self: flex-start;
                    border-radius: 2px;
                    color: #888;
                    background-color: #f7f7f8;
                }
        
                .prices {
                    display: flex;
                    align-items: baseline;
                    margin-top: 3px;
                    font-size: 14px;
        
                    .pay-price {
                        margin-right: 5px;
                        color: #cf4444;
                    }
            
                    .price {
                        font-size: 12px;
                        color: #999;
                        text-decoration: line-through;
                    }
                }
    
                .count {
                    position: absolute;
                    bottom: 0;
                    right: 0;
                    font-size: 13px;
                    color: #444;
                }
            }
        }

        // 配送及支付方式
        .related {
            margin: 10px;
            padding: 0 10px;
            border-radius: 5px;
            background-color: #fff;
        
            .item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                min-height: 40px;
                font-size: 13px;
                color: #333;
            }
        
            .input {
                flex: 1;
                text-align: right;
                margin: 10px 0;
                padding-right: 10px;
                font-size: 13px;
                color: #999;
            }
        
            .item .text {
                width: 63px;
            }
        
            .picker {
                color: #666;
            }
        
            .picker::after {
                font-family: 'iconfont' !important;
                content: '\e607';
            }
        }

        // 结算清单
        .settlement {
            margin: 10px;
            padding: 0 10px;
            border-radius: 5px;
            background-color: #fff;
            .item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                height: 40px;
                font-size: 13px;
                color: #333;
            }
            .danger {
                color: #cf4444;
            }
        }
    }

}
  
.symbol::before {
    content: '¥';
    font-size: 80%;
    margin-right: 2.5px;
}

// 吸底工具栏
.toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;

    background-color: #fff;
    height: 50px;
    padding: 0 10px;
    border-top: 1px solid #eaeaea;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: content-box;
    .total-pay {
        font-size: 20px;
        color: #cf4444;
        .decimal {
            font-size: 75%;
        }
    }
    .button {
        width: 110px;
        text-align: center;
        line-height: 36px;
        font-size: 13px;
        color: #fff;
        border-radius: 36px;
        background-color: #27ba9b;
    }
    .disabled {
        opacity: 0.6;
    }
}
  
.address-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px;
    width: 100%;
    .title {
        font-weight: bold;
    }
    .close {
        font-size: 22px;
        color: #27ba9b;
    }
}
// 收货地址
.address-list {
    padding: 0 10px;
    background-color: #fff;
    border-top: 1px solid gainsboro;
    .item-content {
        display: flex;
        align-items: center;
        line-height: 1;
        padding: 20px 10px;
        position: relative;
        margin: 10px 0;
        border-radius: 5px;
        box-shadow: 0 0 5px gray;
        .address-icon {
            font-size: 24px;
        }
        .address-box {
            display: flex;
            flex-direction: column;
            width: 100%;
            .address-name-box {
                display: flex;
                justify-content: center;
                align-items: center;
                justify-content: space-between;
            }
            .address-contact {
                font-size: 14px;
                padding: 7px 0px;
            }
            .address-locate {
                font-size: 14px;
            }
        }
        &.active {
            border: 2px solid #27ba9b;
        }
        .edit {
            position: absolute;
            top: 18px;
            right: 15px;
            padding: 1px 0 1rpx 10px;
            border-left: 1px solid #666;
            font-size: 13px;
            color: #666;
            line-height: 1;
        }
    }
    .address-add-btn {
        text-align: center;
        margin: 15px 0;
    }

    .address-user {
        display: flex;
        justify-content: space-between;
        font-size: 14px;
        margin-bottom: 10px;
        color: #333;
        .address-name {
            font-size: 16px;
            font-weight: bold;
        }
        .contact {
            color: #666;
        }

        .badge {
            padding: 2px 5px 1px 7px;
            margin-right: 5px;
            font-size: 13px;
            color: #27ba9b;
            border-radius: 3px;
            border: 1px solid #27ba9b;
        }
    }

    .locate {
        line-height: 1.6;
        font-size: 13px;
        color: #333;
    }
}
</style>